<!-- @format -->

<template>
  <div class="page-container">
    <page_breadcrumb :getKeyMethod="init_table_model" @change="change_table_model" pageOption />
    <ex_super_table_page v-bind="option" ref="SuperTablePage" @selection-change="(e) => (selection = e)" @search="searchChange"> </ex_super_table_page>

    <ex_super_dialog_form ref="sync_dialog" v-bind="sync_dialog" @afterSubmitSuccess="reload()"> </ex_super_dialog_form>
    <ex_super_dialog_form ref="uploadFileDialog" v-bind="upload_file_dialog" @afterSubmitSuccess="reload()"> </ex_super_dialog_form>
  </div>
</template>
<script>
import superTablePageFunction from "@/mixin/super-table-page-function";
import emitOnFunction from "@/mixin/emit-on-function";

import page_table_model_manage from "@/mixin/page_table_model_manage";
let emitKey = "platformSync>order_list";

export default {
  title: "label_ozon_order_list",
  mixins: [superTablePageFunction, emitOnFunction(emitKey), page_table_model_manage],
  components: {},
  data() {
    return {
      orderStatus: "",
      orderData: {
        waitSubmitCount: null,
        completeSubmitCount: null,
        submitFailCount: null,
        exceptionCount: null,
        canceledCount: null,
      },
      status_map: {
        WAIT_SUBMIT: "waitSubmitCount",
        COMPLETE_SUBMIT: "completeSubmitCount",
        SUBMIT_FAIL: "submitFailCount",
        EXCEPTION: "exceptionCount",
        CANCELED: "canceledCount",
        COMPLETE: "computeCount",
      },
      selection: [],
      option: {
        search: {
          default: { orderStatus: "" },
          model: [
            {
              key: "orderStatus",
              label: "label_status",
              itemClass: "w_fill",
              render: (h, { data }) => {
                let enums = this.$enumOptions["SrmOrderStatusEnum"] || [];

                const list = enums.map((it) => (
                  <el-radio-button key={it} label={it}>
                    {this.$enumShow(it, "SrmOrderStatusEnum")}
                    {this.status_map[it] && this.orderData[this.status_map[it]] ? `(${this.orderData[this.status_map[it]]})` : "(0)"}
                  </el-radio-button>
                ));
                return (
                  <el-radio-group
                    value={data.orderStatus}
                    onInput={(e) => {
                      this.orderStatus = e;
                      this.$set(data, "orderStatus", e);
                      this.$refs.SuperTablePage.loadDataForSearch();
                    }}
                  >
                    <el-radio-button key="" label="">
                      {this.$tt("label_all")}
                    </el-radio-button>
                    {list}
                  </el-radio-group>
                );
              },
            },
            { key: "postingNumber", label: "label_platform_code" },
            { key: "clientId", label: "label_platform_store" },
            { key: "trackNumber", label: "label_track_code" },
            { key: "omsOrderNo", label: "label_outbound_code" },
          ],
        },
        action: [
          {
            label: "label_submit_order",
            attrs: { type: "primary" },
            if: () => ["", "WAIT_SUBMIT", "SUBMIT_FAIL"].includes(this.orderStatus),
            click: (e) => this.submitOrder(this.selection),
          },
          {
            label: "label_cancel_order",
            if: () => ["", "WAIT_SUBMIT", "SUBMIT_FAIL"].includes(this.orderStatus),

            attrs: { type: "danger" },
            click: (e) => this.cancelOrder(this.selection),
          },
          {
            label: "label_retry_order",
            if: () => ["", "WAIT_SUBMIT", "SUBMIT_FAIL",  "EXCEPTION"].includes(this.orderStatus),
            attrs: { type: "warning" },
            click: (e) => this.retryOrder(this.selection),
          },
          {
            label: "label_sync_order",
            if: () => ["", "WAIT_SUBMIT", "SUBMIT_FAIL"].includes(this.orderStatus),
            click: () => {
              this.$refs.sync_dialog.showNew({
                title: this.$tt("label_sync_order"),
                params: {
                  platformCode: "OZON",
                  businessType: "FBS",
                },
              });
            },
          },
          {
            label: "label_upload_handover_order",
            if: () => ["", "COMPLETE_SUBMIT"].includes(this.orderStatus),

            click: () => {
              if (_.isEmpty(this.selection)) return this.$message.error(this.$tt("tip_please_select_order"));
              this.$refs.uploadFileDialog.showNew({
                title: this.$tt("label_upload_handover_order"),
                data: {
                  orders: this.selection,
                },
              });
            },
          },
        ],

        table: {
          url: this.$url["srm/OzonOrderSyncPage"],

          model: this.init_table_model(),
        },
      },
      // 全部、草稿、待收货、已收货、处理中、已完成

      upload_file_dialog: {
        customClass: "dialog_auto",
        submitUrl: "/srm-api/ozon/OzonOrderClientRpc/uploadDeliveryReceiptFile.json",
        submitDataHandle: (data) => {
          return {
            fileName: _.head(data.attachedList).fileName,
            filePath: _.head(data.attachedList).filePath,
            remark: data.remark,
            srmOzonOrderDTOs: data.orders.map((it) => ({
              postingNumber: it.postingNumber,
              trackingNumber: it.trackingNumber,
            })),
          };
        },
        form: {
          // itemClass: "form_item_default", inputClass: "form_input_default",

          default: {
            attachedList: [],
            orders: [],
          },
          model: [
            { header: "label_base_info" },
            {
              key: "tip",
              label: "label_illustrate",
              formType: "text",
              formatter: (r, c, v) => this.$tt("tip_xxx_has_select_count_order_upload_handover_order", { count: r.orders.length }),
            },
            {
              key: "remark",
              label: "label_remark",
            },
            {
              key: "attachedList",
              label: "label_attachment",
              render: (h, { data }) => {
                return h("ex_super_upload", {
                  props: {
                    limit: 1,
                    type: "file",
                    accept: ".pdf",
                    value: data.attachedList,
                  },
                  on: {
                    input: (list) => {
                      this.$set(data, "attachedList", list);
                    },
                  },
                });
              },
            },
          ],
          rules: {
            attachedList: { required: true, type: "array", message: this.$tt("tip_can_no_empty") },
          },
        },
      },
      sync_dialog: {
        customClass: "dialog_auto",
        submitUrl: "/srm-api/ozon/OzonOrderClientRpc/syncOrder.json",
        detailUrl: "/ums-api/client/ThirdPartyAuthorizedClientRpc/selectList.json",
        detailDataHandle: (data) => {
          return {
            auths: data.rows,
          };
        },
        submitType: "form",
        submitDataHandle: (data) => {
          return {
            clientId: data.clientId,
            apiKey: data.apiKey,
            startDate: data.limitDate[0],
            endDate: data.limitDate[1],
          };
        },
        form: {
          // itemClass: "form_item_default", inputClass: "form_input_default",

          default: {
            auths: [],
          },
          model: [
            { header: "label_base_info" },
            {
              key: "limitDate",
              label: "label_order_time",
              type: "date-picker",
              attrs: {
                clearable: false,
                type: "datetimerange",
                "default-time": ["00:00:00", "23:59:59"],
                "picker-options": {
                  shortcuts: this.$date_range_shortcuts(),
                },
              },
            },
            {
              key: "apiKey",
              label: "clientId",
              render: (h, { data }) => {
                if (_.isEmpty(data.auths)) {
                  return (
                    <div class="flex_row_center">
                      <span> {this.$t("tip_none_clientId_is_goto")} </span>
                      <el-link
                        type="primary"
                        onClick={(e) => {
                          this.$router.push({ name: "/page/ums/setting/thirdParty_authorized_manage" });
                          this.$refs.sync_dialog.visible = false;
                        }}
                      >
                        {this.$t("label_thirdParty_authorized")}
                      </el-link>
                    </div>
                  );
                }
                return h("ex_select_auto", {
                  class: "w_fill",
                  props: {
                    value: data.apiKey,
                    items: data.auths,
                    option: { label: "sellerId", value: "apiKeys" },
                  },
                  on: {
                    changeItem: (e) => {
                      this.$set(data, "clientId", e.sellerId);
                      this.$set(data, "apiKey", e.apiKeys);
                    },
                  },
                });
              },
            },
          ],
          rules: {
            limitDate: { required: true, message: this.$tt("tip_can_no_empty") },
            apiKey: { required: true, message: this.$tt("tip_can_no_empty") },
          },
        },
      },
    };
  },
  methods: {
    option_table_model() {
      return [
        { type: "selection", clickToggle: true, keyGroup: "label_table_operate" },
        {
          type: "expandDesc",
          width: 100,
          expandDesc: {
            ...this.$defaultDescAttrs,
            model: [],
          },
        },
        { key: "omsOrderNo", label: "label_outbound_code", width: 140 },

        { key: "orderNumber", label: "label_order_code", "show-overflow-tooltip": true },
        { key: "postingNumber", label: "label_platform_code", "show-overflow-tooltip": true },
        { key: "clientId", label: "label_platform_store", width: 110, "show-overflow-tooltip": true },
        { key: "trackNumber", label: "label_track_code", width: 110, "show-overflow-tooltip": true },
        { key: "customerCountry", label: "label_consignee_country", width: 110, "show-overflow-tooltip": true },
        { key: "customerName", label: "label_consignee_person_name", width: 110, "show-overflow-tooltip": true },
        { key: "customerPhone", label: "label_consignee_person_phone", width: 110, "show-overflow-tooltip": true },
        { key: "customerAddress", label: "label_consignee_address", width: 110, "show-overflow-tooltip": true },
        { key: "trackingNumber", label: "label_track_code", width: 110, "show-overflow-tooltip": true },

        {
          key: "orderStatus",
          label: "label_status",
          width: 120,
          "show-overflow-tooltip": true,
          formatter: (r, c, v, i) => this.$enumShow(v, "SrmOrderStatusEnum"),
        },
        {
          key: "exceptionMsg",
          label: "label_exception_info",
          width: 120,
          render: (h, { row, column }) => {
            const code = row[column.property];
            if (!code) return this.$tt("data_temp_none");
            return <text_extra_tooltip_operate value={code} ellipsis data_type={column.property} data_id={row.id} />;
          },
        },
        { key: "gmtCreate", label: "label_create_time", formatter: (r, c, v, i) => this.$dateFormat(v) },
        {
          type: "operate",
          width: 220,
          fixed: "right",
          operate: [
            { label: "label_view_detail", click: (row) => this.clickDetail(row) },
            {
              type: "more",
              items: [
                {
                  label: "label_submit_order",
                  disabled: (row) => !["WAIT_SUBMIT", "SUBMIT_FAIL", "CANCELED"].includes(row.orderStatus), //'COMPLETE_SUBMIT', 'SUBMIT_FAIL', 'EXCEPTION', 'CANCELED'
                  click: (row) => this.submitOrder([row]),
                },
                {
                  label: "label_retry_order",
                  if: (row) => [ "WAIT_SUBMIT", "SUBMIT_FAIL","EXCEPTION"].includes(row.orderStatus),
                  disabled: (row) => ![ "WAIT_SUBMIT", "SUBMIT_FAIL","EXCEPTION"].includes(row.orderStatus), //'COMPLETE_SUBMIT', 'SUBMIT_FAIL', 'EXCEPTION', 'CANCELED'
                  click: (row) => this.retryOrder([row]),
                },
          
                
                {
                  label: "label_cancel_order",
                  disabled: (row) => !["WAIT_SUBMIT", "SUBMIT_FAIL", "EXCEPTION"].includes(row.orderStatus),
                  click: (row) => this.cancelOrder([row]),
                },
              ],
            },
            // {
            //   label: 'label_delete', type: "confirm-button", buttonClass: "button_text_danger", confirmButtonType: 'danger',
            //   url: this.$url['oms/ReturnOrderRemove'], message: 'text_confirm_sure_delete',
            //   params: (v) => { return { id: v.id } }, done: ['reload', 'tip']
            // },
          ],
        },
      ];
    },
    clickDetail(row) {
      this.$router.push({
        path: "/page/oms/platformSync/sync_order_detail",
        query: { id: row.id },
      });
    },
    searchChange() {
      if (!this.orderStatus) {
        this.$ajax({
          url: this.$url["srm/OzonOrderSyncStatCount"],
          method: "post",
          data: this.$refs.SuperTablePage.getSearchFormData(),
          success: (res) => {
            this.orderData = res.data;
          },
        });
      }
    },
    cancelOrder(rows) {
      if (_.isEmpty(rows)) return this.$message.error(this.$tt("tip_please_select_order"));
      if (rows.some((it) => !["WAIT_SUBMIT", "SUBMIT_FAIL", "EXCEPTION"].includes(it.orderStatus))) return this.$message.error(this.$tt("tip_part_order_status_error_no_operate"));
      this.$confirm(this.$tt("tip_xxx_confirm_cancel_select_order", { count: rows.length }), this.$tt("label_tip"), {
        type: "warning",
      })
        .then(() => {
          this.$ajax({
            url: this.$url["srm/OzonOrderSyncCancel"],
            method: "post",
            type: "json",
            loading: true,
            data: {
              orderIds: rows.map((it) => it.id),
            },
            success: (res) => {
              this.$message({
                showClose: true,
                message: this.$tt("tip_submit_success"),
                type: "success",
              });
              this.reload();
            },
          });
        })
        .catch(() => {});
    },

    submitOrder(rows) {
      if (_.isEmpty(rows)) return this.$message.error(this.$tt("tip_please_select_order"));
      if (rows.some((it) => !["WAIT_SUBMIT", "SUBMIT_FAIL", "CANCELED"].includes(it.orderStatus))) return this.$message.error(this.$tt("tip_part_order_status_error_no_operate"));

      this.$confirm(this.$tt("tip_xxx_confirm_submit_select_order", { count: rows.length }), this.$tt("label_tip"), {
        type: "warning",
      })
        .then(() => {
          this.$ajax({
            url: this.$url["srm/OzonOrderSyncSubmit"],
            method: "post",
            type: "json",
            loading: true,
            data: {
              orderIds: rows.map((it) => it.id),
            },
            success: (res) => {
              this.$message({
                showClose: true,
                message: this.$tt("tip_submit_success"),
                type: "success",
              });
              this.reload();
            },
          });
        })
        .catch(() => {});
    },
    retryOrder(rows) {
      if (_.isEmpty(rows)) return this.$message.error(this.$tt("tip_please_select_order"));
      if (rows.some((it) => !["WAIT_SUBMIT", "SUBMIT_FAIL","EXCEPTION"].includes(it.orderStatus))) return this.$message.error(this.$tt("tip_part_order_status_error_no_operate"));

      this.$confirm(this.$tt("tip_xxx_confirm_retry_select_order", { count: rows.length }), this.$tt("label_tip"), {
        type: "warning",
      })
        .then(() => {
          this.$ajax({
            url: this.$url["srm/OzonOrderSyncRetry"],
            method: "post",
            type: "json",
            loading: true,
            data: {
              orderIds: rows.map((it) => it.id),
            },
            success: (res) => {
              this.$message({
                showClose: true,
                message: this.$tt("tip_submit_success"),
                type: "success",
              });
              this.reload();
            },
          });
        })
        .catch(() => {});
    },

  },
};
</script>
<style></style>
